<template>
  <el-container>
    <el-header>
      <div class="left-panel">
        <div class="right-panel-search">
          <el-input placeholder="名称/手机号" clearable></el-input>
          <el-button type="primary" icon="el-icon-search" @click="search"></el-button>
        </div>
      </div>
      <div class="right-panel">
        <el-button type="primary" icon="el-icon-circle-plus" @click="openDrawer('新增')">新增</el-button>
        <el-button type="primary" icon="el-icon-upload" plain @click="addBatch()">导入用户</el-button>
        <el-button type="primary" icon="el-icon-download" plain @click="downloadFile">导出用户</el-button>
        <el-button type="danger" icon="el-icon-delete" plain @click="deleteBatch()">批量删除</el-button>
      </div>
    </el-header>
    <el-main class="no-padding">
      <MyTable ref="tableRef" :requestApi="getTableList" :init-param="initParam" :data-callback="dataCallback">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column type="expand" width="100" label="查看详情">
          <template #default="{ row }">{{ row.name }}</template>
        </el-table-column>
        <el-table-column label="ID" prop="id" width="80"></el-table-column>
        <el-table-column label="姓名" prop="name" width="150"></el-table-column>
        <el-table-column label="性别" prop="gender" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.gender == 1">男</el-tag>
            <el-tag v-if="row.gender == 2" type="warning">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="手机号码" prop="mobile" width="150"></el-table-column>
        <el-table-column label="身份证" prop="idCard" width="150"></el-table-column>
        <el-table-column label="地址" prop="address" width="200"></el-table-column>
        <el-table-column label="状态" prop="status" width="80">
          <template #default="{ row }">
            <el-switch
              :model-value="row.status"
              :active-value="1"
              :inactive-value="0"
              @click="changeStatus(row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="created_at" width="180"></el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #="scope">
            <el-button type="primary" size="small" link @click="openDrawer('查看', scope.row)">查看</el-button>
            <el-button type="primary" size="small" link @click="openDrawer('编辑', scope.row)">编辑</el-button>
            <el-button type="primary" size="small" link @click="deleteAccount(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </MyTable>
    </el-main>
  </el-container>
  <FromDrawer ref="drawerRef" />
  <ImportExcel ref="dialogRef" />
</template>

<script setup lang="tsx" name="TableBase">
import { ref, reactive } from 'vue'
import { ITableDemo } from '@/api/tableDemo/type'
import { TableDemoApi } from '@/api/tableDemo/index'
import { useHandleData } from '@/hooks/useHandleData'
import { useDownload } from '@/hooks/useDownload'
import { useAuthButtons } from '@/hooks/useAuthButtons'
import { ElMessage, ElMessageBox } from 'element-plus'
import MyTable from '@/components/Table/index.vue'
import ImportExcel from '@/components/ImportExcel/index.vue'
import FromDrawer from '@/views/assembly/table/base/drawer.vue'
import { TableInstance } from '@/components/Table/interface'

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 Table 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params))
  newParams.createTime && (newParams.startTime = newParams.createTime[0])
  newParams.createTime && (newParams.endTime = newParams.createTime[1])
  delete newParams.createTime
  return TableDemoApi.baseList(newParams)
}

// Table 实例
const tableRef = ref<TableInstance>()

// 如果表格需要初始化请求参数，直接定义传给 Table (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 })

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => ({
  list: data.list,
  total: data.total
})

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons()

// 搜索
const search = () => {}

// 删除用户信息
const deleteAccount = async (params: ITableDemo.BaseModel) => {
  await useHandleData(TableDemoApi.baseDelete, { id: [params.id] }, `删除【${params.name}】用户`)
  tableRef.value?.getTableList()
}

// 批量删除用户信息
const deleteBatch = async () => {
  const ids: string[] | undefined = tableRef.value?.selectedListIds
  if (ids && ids.length > 0) {
    await useHandleData(TableDemoApi.baseDelete, { ids }, '删除所选用户信息')
    tableRef.value?.clearSelection()
    tableRef.value?.getTableList()
  } else {
    ElMessage.error('请选择需要操作的行')
  }
}

// 切换用户状态
const changeStatus = async (row: ITableDemo.BaseModel) => {
  await useHandleData(
    TableDemoApi.baseChangeStatus,
    { id: row.id, status: row.status == 1 ? 0 : 1 },
    `切换【${row.name}】用户状态`
  )
  tableRef.value?.getTableList()
}

// 导出用户列表
const downloadFile = async () => {
  ElMessageBox.confirm('确认导出用户数据?', '温馨提示', { type: 'warning' }).then(() =>
    useDownload(TableDemoApi.baseExport, '用户列表', tableRef.value?.searchParam)
  )
}

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null)
const addBatch = () => {
  const params = {
    title: '用户',
    templateApi: TableDemoApi.baseExport,
    importApi: TableDemoApi.baseImport,
    getTableList: MyTable.value?.getTableList
  }
  dialogRef.value?.acceptParams(params)
}

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof FromDrawer> | null>(null)
const openDrawer = (title: string, row: Partial<ITableDemo.BaseModel> = {}) => {
  const params = {
    title,
    isView: title === '查看',
    row: { ...row },
    api: title === '查看' ? undefined : TableDemoApi.baseEdit,
    getTableList: tableRef.value?.getTableList
  }
  drawerRef.value?.acceptParams(params)
}
</script>
